<template>
  <div class="week_play" v-if="dialogVisible">
    <el-dialog
      :title="isNewPlan ? '新增周计划': '修改周计划'"
      width="560px"
      customClass="mes_dialog"
      :visible.sync="dialogVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      @closed="handleClose">
      <div class="step_one mes_file_secret week_play_add" v-if="step === 1">
        <div class="import_item">
          <div class="import_label"><span class="import_required">* </span>文档密级：</div>
          <div class="import_content">
            <el-select v-model="fileSecretLevelId" size="small" placeholder="请选择密级">
              <el-option
                v-for="item in fileSecretLevel"
                :key="item.id"
                :label="item.label"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="import_item">
          <div class="import_label"><span class="import_required">* </span>周计划时间：</div>
          <div class="import_content">
            <el-date-picker
              type="daterange"
              size="small"
              v-model.trim="weekPlanDate"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions"
              :clearable=false
              @change="_currentDate">
            </el-date-picker>
          </div>
        </div>
        <div class="import_item">
          <div class="import_label"><span class="import_required">* </span>周计划名称：</div>
          <div class="import_content">
            <el-input
              v-model.trim="name"
              placeholder="请输入周计划名称"
              maxlength="50"
              size="small"
              :clearable=false>
            </el-input>
          </div>
        </div>
        <div class="import_item">
          <div class="import_label"><span class="import_required">* </span>上传周计划：</div>
          <div class="file_cont import_content">
            <div class="mes_btn">
              <el-button class="file_btn" @click="$refs.fileInput.click()">
                <i class="iconfont icon-btn_addnew"></i>
                <span>选择文件</span>
                <input type="file"
                       ref="fileInput"
                       class="file_input"
                       :accept="accept.toString()"
                       @change="_file">
              </el-button>
              <span class="accept_text">支持{{accept.join('、')}}格式</span>
            </div>
            <div class="file_name_input" v-show="filesData.fileName || filesData.name">
              <i class="el-icon-document"></i>
              <tooltip-txt :text="filesData.fileName || filesData.name"></tooltip-txt>
            </div>
          </div>
        </div>
        <div class="import_item" v-if="!isNewPlan && planStatus !== 'Draft'">
          <div class="import_label">备注：</div>
          <div class="import_content">
            <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入备注"
              v-model="remarks"
              maxlength="255">
            </el-input>
          </div>
        </div>
      </div>
      <div slot="footer" class="mes_btn" v-if="step === 1">
        <el-button type="primary" @click="confirmImport">保 存</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
      <div class="step_two" v-else-if="step === 2"
           v-loading="isLoading"
           element-loading-text="数据校验中">
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WeekPlanAdd',
  props: {
    isNewPlan: {
      type: Boolean,
      default: true
    },
    planStatus: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isLoading: true, // 加载中
      dialogVisible: false, // 弹框显示
      // 文件类型
      accept: ['.doc', '.docx'],
      pickerOptions: {},
      fileSecretLevelId: '', // 文件密级
      importToken: null, // 文件上传token
      filesData: {}, // file服务器信息
      name: '', // 周计划名称
      weekPlanDate: [], // 计划时间
      fileName: '', // 上传文件名称
      step: 1, // 当前步骤
      listId: '', // 列表id
      uploadHistoryId: '',
      newName: '',
      isEdit: false, // 应该是文件是否有变动
      remarks: '', // 周计划备注
    }
  },
  computed: {
    // 文档密级
    fileSecretLevel() {
      return this.$store.state.dict.fileSecretLevel.labels || []
    },
  },
  methods: {
    // 打开方法
    openDialog(list) {
      this.step = 1
      this.dialogVisible = true
      if (list) {
        this.isEdit = true
        let data = list[0]
        this.listId = data.id
        this.fileSecretLevelId = data.fileSecretLevelId
        this.name = data.name
        this.newName = data.name
        this.weekPlanDate = [data.planStartDate, data.planEndDate]
        this.filesData = data
        this.uploadHistoryId = data.uploadHistoryId
      } else {
        this.isEdit = false
        this.fileSecretLevelId = this.defaultFileLevel
        this.name = null
        this.weekPlanDate = []
        this.filesData = {}
        this.listId = ''
      }
      this.remarks = ''
      // this.$nextTick(() => {
      //   this.$refs.fileInput.value = null
      // })
    },
    // 日期选择
    _currentDate(val) {
      let startDate = this.moment(val[0]).format('YYYY-MM-DD')
      let endDate = this.moment(val[1]).format('YYYY-MM-DD')
      let week = this.moment(val[0]).format('W')
      let strConnect = '第' + week + '周' + ' ' + startDate + '~' + endDate
      if (val) {
        this.name = strConnect
      }
    },
    // 选择文件
    _file(e) {
      this.isEdit = false // 为false的时候提交需要上传
      let file = e.target.files[0]
      if (file && /^(\.doc)|(docx)$/.test(file.name.slice(-4).toLowerCase())) {
        this.filesData = file
        e.target.value = null
      } else if (file) {
        this.filesData = {}
        this.tipMessage('error', `文件格式错误，请选择后缀为${this.accept.join('、')}的文件`)
      }
    },
    // 判断是否可以上传
    confirmImport() {
      if (!this.fileSecretLevelId) {
        return this.tipMessage('error', '请先选择文档密级')
      } else if (this.weekPlanDate.length !== 2) {
        return this.tipMessage('error', '请先选择周计划日期')
      } else if (!this.name) {
        return this.tipMessage('error', '请先填写周计划名称')
      } else if (!this.filesData.name && !this.filesData.fileName) {
        return this.tipMessage('error', `请先选择后缀为${this.accept.join('、')}的文件`)
      }
      if (this.name !== this.newName) {
        this.isRepeatName()
        return
      }
      if (this.name !== this.newName && !this.isEdit) {
        this.isRepeatName()
        return
      }
      if (!this.isEdit) {
        this.importFile()
        return
      }
      this.save()
    },
    // 判断文件名是否重复
    async isRepeatName() {
      let postData = {
        method: 'post',
        url: 'a/weekplan/weekPlan/weekPlanNameRepeat',
        data: {
          weekPlanName: this.name
        },
        noCommit: true,
      }
      await this.$store.dispatch('saveData', postData).then(() => {
        if (!this.isEdit) {
          this.importFile()
          return
        }
        this.save()
      })
    },
    // 上传文件
    async importFile() {
      this.isLoading = true
      this.step = 2
      this.importToken = this.$axios.CancelToken.source()
      let formdata = new FormData()
      formdata.append('file', this.filesData)
      formdata.append('fileSecretLevelId', this.fileSecretLevelId)
      await this.$store.dispatch('importFileSave', {
        data: formdata,
        cancelToken: this.importToken.token,
      }).then((res) => {
        this.isLoading = false
        this.uploadHistoryId = res.id
        this.save()
      }).catch(() => {
        this.step = 1
      })
    },
    // 保存
    save() {
      this.isLoading = true
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/weekplan/weekPlan/save2',
        data: {
          uploadHistoryId: this.uploadHistoryId,
          name: this.name,
          remarks: this.remarks || undefined,
          planStartDate: this.weekPlanDate[0],
          fileSecretLevelId: this.fileSecretLevelId,
          planEndDate: this.weekPlanDate[1],
          fileName: this.filesData.fileName,
          id: this.listId || ''
        },
        noCommit: true
      }).then(() => {
        this.isLoading = false
        this.dialogVisible = false
        this.tipMessage('success', '提交成功')
        this.$emit('submitSuccess')
      })
    },
    // 关闭弹框
    handleClose() {
      this.dialogVisible = false
      this.step = 1
      this.remarks = ''
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
  ,
}
</script>

<style scoped lang="less">
  .week_play {
    .mes_file_secret .import_item .import_label {
      flex: 0 0 95px;
      text-align: right;
    }
    .import_content {
      width: 100%;
      .el-date-editor.el-range-editor.el-input__inner.el-date-editor--daterange.el-range-editor--small,
      .el-select.el-select--small {
        width: 100% !important;
      }
    }
    .step_two {
      height: 228px;
    }
  }
</style>
